import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../widgets/platform/adaptive_button.dart';

/// 知识图谱页面
class KnowledgeGraphPage extends ConsumerStatefulWidget {
  const KnowledgeGraphPage({super.key});

  @override
  ConsumerState<KnowledgeGraphPage> createState() => _KnowledgeGraphPageState();
}

class _KnowledgeGraphPageState extends ConsumerState<KnowledgeGraphPage> {
  final List<_GraphNode> _nodes = [
    _GraphNode(
      id: '1',
      title: '项目A',
      type: _NodeType.project,
      x: 100,
      y: 100,
    ),
    _GraphNode(
      id: '2',
      title: '待办任务1',
      type: _NodeType.todo,
      x: 250,
      y: 150,
    ),
    _GraphNode(
      id: '3',
      title: '需求分析会议',
      type: _NodeType.note,
      x: 400,
      y: 100,
    ),
    _GraphNode(
      id: '4',
      title: '技术方案设计',
      type: _NodeType.note,
      x: 300,
      y: 250,
    ),
    _GraphNode(
      id: '5',
      title: '后端API开发',
      type: _NodeType.todo,
      x: 150,
      y: 300,
    ),
  ];

  final List<_GraphEdge> _edges = [
    _GraphEdge(source: '1', target: '2', label: '包含'),
    _GraphEdge(source: '2', target: '3', label: '相关'),
    _GraphEdge(source: '2', target: '4', label: '生成'),
    _GraphEdge(source: '1', target: '5', label: '包含'),
    _GraphEdge(source: '4', target: '5', label: '指导'),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('知识图谱'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              // 刷新图谱数据
              setState(() {});
            },
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              // 添加新节点
              _showAddNodeDialog(context);
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 工具栏
          _buildToolbar(),
          // 图谱视图
          Expanded(
            child: _buildGraphView(),
          ),
        ],
      ),
    );
  }

  /// 构建工具栏
  Widget _buildToolbar() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        children: [
          AdaptiveButton(
            onPressed: () {
              // 放大
            },
            child: const SelectableText('放大'),
          ),
          const SizedBox(width: 8),
          AdaptiveButton(
            onPressed: () {
              // 缩小
            },
            child: const SelectableText('缩小'),
          ),
          const SizedBox(width: 8),
          AdaptiveButton(
            onPressed: () {
              // 重置视图
            },
            child: const SelectableText('重置'),
          ),
          const SizedBox(width: 16),
          const SelectableText('搜索:'),
          const SizedBox(width: 8),
          Expanded(
            child: TextField(
              decoration: const InputDecoration(
                hintText: '搜索节点...',
                prefixIcon: Icon(Icons.search),
                border: OutlineInputBorder(),
              ),
              onSubmitted: (value) {
                // 执行搜索
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建图谱视图
  Widget _buildGraphView() {
    return InteractiveViewer(
      boundaryMargin: const EdgeInsets.all(1000),
      minScale: 0.1,
      maxScale: 3.0,
      child: Container(
        color: Colors.grey[100],
        child: CustomPaint(
          size: const Size(800, 600),
          painter: _GraphPainter(_nodes, _edges),
        ),
      ),
    );
  }

  /// 显示添加节点对话框
  void _showAddNodeDialog(BuildContext context) {
    final titleController = TextEditingController();
    _NodeType selectedType = _NodeType.note;

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('添加节点'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: titleController,
              decoration: const InputDecoration(labelText: '标题'),
            ),
            const SizedBox(height: 16),
            const SelectableText('类型:'),
            Wrap(
              spacing: 8.0,
              children: _NodeType.values.map((type) {
                return ChoiceChip(
                  label: SelectableText(_getNodeTypeName(type)),
                  selected: selectedType == type,
                  onSelected: (selected) {
                    if (selected) {
                      selectedType = type;
                    }
                  },
                );
              }).toList(),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const SelectableText('取消'),
          ),
          TextButton(
            onPressed: () {
              if (titleController.text.isNotEmpty) {
                setState(() {
                  _nodes.add(_GraphNode(
                    id: DateTime.now().millisecondsSinceEpoch.toString(),
                    title: titleController.text,
                    type: selectedType,
                    x: 200 + (DateTime.now().millisecond % 200),
                    y: 200 + (DateTime.now().millisecond % 200),
                  ));
                });
                Navigator.pop(context);
              }
            },
            child: const SelectableText('添加'),
          ),
        ],
      ),
    );
  }

  /// 获取节点类型名称
  String _getNodeTypeName(_NodeType type) {
    switch (type) {
      case _NodeType.project:
        return '项目';
      case _NodeType.todo:
        return '任务';
      case _NodeType.note:
        return '笔记';
      default:
        return '未知';
    }
  }
}

/// 节点类型枚举
enum _NodeType {
  project,
  todo,
  note,
}

/// 图节点
class _GraphNode {
  final String id;
  final String title;
  final _NodeType type;
  final double x;
  final double y;

  _GraphNode({
    required this.id,
    required this.title,
    required this.type,
    required this.x,
    required this.y,
  });
}

/// 图边
class _GraphEdge {
  final String source;
  final String target;
  final String label;

  _GraphEdge({
    required this.source,
    required this.target,
    required this.label,
  });
}

/// 图绘制器
class _GraphPainter extends CustomPainter {
  final List<_GraphNode> nodes;
  final List<_GraphEdge> edges;

  _GraphPainter(this.nodes, this.edges);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..strokeWidth = 2
      ..style = PaintingStyle.stroke;

    final textPainter = TextPainter(
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr,
    );

    // 绘制边
    for (final edge in edges) {
      final sourceNode = nodes.firstWhere((node) => node.id == edge.source);
      final targetNode = nodes.firstWhere((node) => node.id == edge.target);

      // 绘制连线
      paint.color = Colors.blueGrey;
      canvas.drawLine(
        Offset(sourceNode.x, sourceNode.y),
        Offset(targetNode.x, targetNode.y),
        paint,
      );

      // 绘制标签
      textPainter.text = TextSpan(
        text: edge.label,
        style: const TextStyle(color: Colors.black, fontSize: 12),
      );
      textPainter.layout();
      textPainter.paint(
        canvas,
        Offset(
          (sourceNode.x + targetNode.x) / 2 - textPainter.width / 2,
          (sourceNode.y + targetNode.y) / 2 - textPainter.height / 2,
        ),
      );
    }

    // 绘制节点
    for (final node in nodes) {
      // 根据类型设置颜色
      Color color;
      double radius;
      switch (node.type) {
        case _NodeType.project:
          color = Colors.blue;
          radius = 30;
          break;
        case _NodeType.todo:
          color = Colors.green;
          radius = 25;
          break;
        case _NodeType.note:
          color = Colors.orange;
          radius = 20;
          break;
      }

      // 绘制节点圆形
      paint.color = color;
      paint.style = PaintingStyle.fill;
      canvas.drawCircle(Offset(node.x, node.y), radius, paint);

      // 绘制边框
      paint.color = Colors.black;
      paint.style = PaintingStyle.stroke;
      canvas.drawCircle(Offset(node.x, node.y), radius, paint);

      // 绘制标题
      textPainter.text = TextSpan(
        text: node.title,
        style: const TextStyle(color: Colors.black, fontSize: 12),
      );
      textPainter.layout();
      textPainter.paint(
        canvas,
        Offset(
          node.x - textPainter.width / 2,
          node.y - textPainter.height / 2,
        ),
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
